/*
 * @Description:
 * @Author: qingyang
 * @Date: 2022-10-17 14:06:44
 * @LastEditors: qingyang
 * @LastEditTime: 2022-11-16 17:44:37
 */
import { ref, reactive, toRaw } from 'vue';
import { useMessage } from '@/hooks/useMessage';
import type {
  GetAdTaskDetailResult,
  AdTaskDataInfoListItem
} from '@/apis/todo/model/flowBusinessModel';
import { getAdTaskDetail } from '@/apis/todo/flowBusiness';
import type { IFileItem } from './components/types';
import { handleScrollToErrorPosition } from '@/utils';
import { EmissionCategoryEnum, EmissionCategoryMap, OrgTagEnum } from '@/constants/enum';
import { isNumber } from '@/utils/is';
import { cloneDeep } from 'lodash';

interface AdTaskListRow extends AdTaskDataInfoListItem {
  isError?: boolean;
}

export const useActiveDataFill = (
  taskNo: string,
  handleUpdateCollapseOptions: (options: any[]) => void,
  handleGetDataSuccess: () => void
) => {
  const { createMessage } = useMessage();
  const isOfficeFlag = ref(false);
  const formState = reactive({
    yield: '',
    workDay: ''
  });
  const loading = ref(false);
  const formRef = ref();
  const table1 = ref<AdTaskListRow[]>([]);
  const table2 = ref<AdTaskListRow[]>([]);
  const table3 = ref<AdTaskListRow[]>([]);
  const adTaskDetail = ref<GetAdTaskDetailResult>();
  const fileList = ref<IFileItem[]>([]);

  /**
   * 提交
   * @param needValidForm 是否需要校验表单
   * @returns
   */
  const handleSubmit = async (needValidForm = true) => {
    try {
      const dataList = [...table1.value, ...table2.value, ...table3.value];
      if (needValidForm) {
        // 是否有记录为空
        let emptyFlag = false;
        dataList.forEach(item => {
          if (!(item.activityData || item.activityData === 0)) {
            item.isError = true;
            emptyFlag = true;
          }
        });
        console.log('dataList', dataList, emptyFlag);
        if (emptyFlag) {
          createMessage.error('活动数据不能为空！');
          // 滚动到错误位置
          handleScrollToErrorPosition('.active-data-fill-container');
          return Promise.reject('活动数据不能为空！');
        }
        // 不是组织办公标签
        if (!isOfficeFlag.value) {
          const valid = await formRef.value.validate();
          console.log('表单检验', valid);
          if (valid) {
            return Promise.resolve(generateBusinessParams());
          }
        }
      } else {
        dataList.forEach(item => {
          item.isError = false;
        });
      }
      return Promise.resolve(generateBusinessParams());
    } catch (error) {
      if (typeof error !== 'string') {
        handleScrollToErrorPosition('.active-data-fill-container');
      }
      return Promise.reject(error);
    }
  };

  const loadDataRow = async (tableName?: string, dataNo?: string) => {
    const table1Data1 = [] as AdTaskListRow[];
    const table1Data2 = [] as AdTaskListRow[];
    const table1Data3 = [] as AdTaskListRow[];
    loading.value = true;
    try {
      const data = await getAdTaskDetail(taskNo);
      if (data.dataInfoList?.length) {
        const options: any = {};
        data.dataInfoList.forEach(item => {
          switch (item.emissionScope) {
            case 'SCOPE_ONE':
              table1Data1.push(item);
              if (!options['SCOPE_ONE']) {
                options['SCOPE_ONE'] = {
                  title: `范围一${
                    EmissionCategoryMap[item.emissionCategory as keyof typeof EmissionCategoryEnum]
                  }`,
                  key: 'SCOPE_ONE',
                  defaultOpened: true
                };
              }

              break;
            case 'SCOPE_TWO':
              table1Data2.push(item);
              if (!options['SCOPE_TWO']) {
                options['SCOPE_TWO'] = {
                  title: `范围二${
                    EmissionCategoryMap[item.emissionCategory as keyof typeof EmissionCategoryEnum]
                  }`,
                  key: 'SCOPE_TWO',
                  defaultOpened: true
                };
              }
              break;
            case 'SCOPE_THREE':
              table1Data3.push(item);
              if (!options['SCOPE_THREE']) {
                options['SCOPE_THREE'] = {
                  title: `范围三${
                    EmissionCategoryMap[item.emissionCategory as keyof typeof EmissionCategoryEnum]
                  }`,
                  key: 'SCOPE_THREE',
                  defaultOpened: true
                };
              }
              break;
          }
        });
        if (tableName == 'table1') {
          const index = table1Data1.findIndex(item => item.dataNo == dataNo);
          if (index > -1) {
            const dataOrigin = toRaw(cloneDeep(table1.value));
            dataOrigin[index].dataSource = table1Data1[index].dataSource;
            dataOrigin[index].activityData = table1Data1[index].activityData;
            table1.value = dataOrigin;
          }
        }
        if (tableName == 'table2') {
          const index = table1Data2.findIndex(item => item.dataNo == dataNo);
          if (index > -1) {
            const dataOrigin = toRaw(cloneDeep(table2.value));
            dataOrigin[index].dataSource = table1Data2[index].dataSource;
            dataOrigin[index].activityData = table1Data2[index].activityData;
            table2.value = dataOrigin;
          }
        }
        if (tableName == 'table3') {
          const index = table1Data3.findIndex(item => item.dataNo == dataNo);
          if (index > -1) {
            const dataOrigin = toRaw(cloneDeep(table3.value));
            dataOrigin[index].dataSource = table1Data3[index].dataSource;
            dataOrigin[index].activityData = table1Data3[index].activityData;
            table3.value = dataOrigin;
          }
        }
        handleUpdateCollapseOptions(Object.keys(options).length ? Object.values(options) : []);
      }
    } finally {
      loading.value = false;
    }
  };
  const loadData = async () => {
    table1.value = [];
    table2.value = [];
    table3.value = [];
    loading.value = true;
    try {
      const data = await getAdTaskDetail(taskNo);
      // 组织是否是办公标签
      isOfficeFlag.value = data.organizationTag === OrgTagEnum.OFFICE;
      adTaskDetail.value = data;
      fileList.value = data.attachmentInfoList.map(item => {
        return {
          name: item.attachmentName,
          url: item.url,
          id: item.attachmentNo
        };
      });
      console.log('loadData', data);
      if (data.yield || isNumber(data.yield)) {
        formState.yield = data.yield;
      } else {
        formState.yield = '';
      }
      if (data.workDay || isNumber(data.workDay)) {
        formState.workDay = data.workDay;
      } else {
        formState.workDay = '';
      }
      if (data.dataInfoList?.length) {
        const options: any = {};
        data.dataInfoList.forEach(item => {
          switch (item.emissionScope) {
            case 'SCOPE_ONE':
              table1.value.push(item);
              if (!options['SCOPE_ONE']) {
                options['SCOPE_ONE'] = {
                  title: `范围一${
                    EmissionCategoryMap[item.emissionCategory as keyof typeof EmissionCategoryEnum]
                  }`,
                  key: 'SCOPE_ONE',
                  defaultOpened: true
                };
              }

              break;
            case 'SCOPE_TWO':
              table2.value.push(item);
              if (!options['SCOPE_TWO']) {
                options['SCOPE_TWO'] = {
                  title: `范围二${
                    EmissionCategoryMap[item.emissionCategory as keyof typeof EmissionCategoryEnum]
                  }`,
                  key: 'SCOPE_TWO',
                  defaultOpened: true
                };
              }
              break;
            case 'SCOPE_THREE':
              table3.value.push(item);
              if (!options['SCOPE_THREE']) {
                options['SCOPE_THREE'] = {
                  title: `范围三${
                    EmissionCategoryMap[item.emissionCategory as keyof typeof EmissionCategoryEnum]
                  }`,
                  key: 'SCOPE_THREE',
                  defaultOpened: true
                };
              }
              break;
          }
        });
        handleUpdateCollapseOptions(Object.keys(options).length ? Object.values(options) : []);
      }
      // NOTE 用于在盘查详情页内查看需要
      handleGetDataSuccess();
    } finally {
      loading.value = false;
    }
  };
  loadData();

  /**
   * 生成工作流业务参数
   */
  function generateBusinessParams() {
    const dataList = [...table1.value, ...table2.value, ...table3.value];
    console.log('fileList', fileList);
    const attachmentList = fileList.value.map(item => {
      return {
        attachmentName: item.name,
        url: item.url
      };
    });
    // activityData如果是空字符串，则替换成null
    const dataMap = dataList.map(item => {
      return {
        ...item,
        activityData: item.activityData === '' ? null : item.activityData
      };
    });
    const params = {
      taskNo,
      dataInfoList: dataMap,
      attachmentInfoList: attachmentList
    };

    // NOTE 办公标签，传参0
    if (isOfficeFlag.value) {
      Object.assign(params, {
        yield: 0,
        workDay: 0
      });
    } else {
      Object.assign(params, {
        yield: formState.yield,
        workDay: formState.workDay
      });
    }

    return params;
  }

  return {
    formState,
    loading,
    handleSubmit,
    formRef,
    fileList,
    adTaskDetail,
    table1,
    table2,
    table3,
    loadData,
    loadDataRow,
    isOfficeFlag
  };
};
